<template>
  <baseModal
    :width="modAlProps.width"
    :isVisible="dislogVisible"
    :title="
      formState[props.uploadType] ? formState[props.uploadType].title : '上传'
    "
    :isCancleBtn="true"
    @handleOk="handleOk"
    @handleCancle="handleCancle"
    :buttons="buttons"
    class="uploadDialong"
  >
    <template v-slot:body>
      <baseTabs
        @changeTabs="changeTopTabs"
        :activeKey="uploadType"
        :tabsList="tabsList"
        style="margin-top: -16px"
      >
      </baseTabs>
      <div v-if="uploadType == 1">
        <div class="flex">
          <span class="lables">选择文件:</span>
          <div>
            <uploadFile
              :fileList="fileList_temp"
              :maxCount="1"
              :accept="fileLimit.img.uploadPicSuffix"
              :isLimit="fileLimit.img.uploadPicSize"
              :title="formState[props.uploadType].uploadTitle"
              :isAutoUpload="formState[props.uploadType].isAutoUpload"
              @uploadChangeFinished="uploadChangeFinished"
              v-if="props.uploadType == 'simpleupload'"
              :percent="percent"
            >
            </uploadFile>

            <multiPictureUpload
              :fileList="fileList_temp"
              :maxCount="props.maxCount || 1000000000"
              :accept="fileLimit.img.uploadPicSuffix"
              :isLimit="fileLimit.img.uploadPicSize"
              :title="formState[props.uploadType].uploadTitle"
              :isAutoUpload="formState[props.uploadType].isAutoUpload"
              :listType="formState[props.uploadType].listType"
              @uploadChangeFinished="uploadChangeFinished"
              v-if="props.uploadType == 'insertimage'"
              @addDescription="addDescription"
              :description="props.description"
            >
            </multiPictureUpload>
            <videoUpload
              ref="videoUploadRef"
              :fileList="fileList_temp"
              :maxCount="1"
              :accept="fileLimit.insertvideo.uploadVideoSuffix"
              :isLimit="fileLimit.insertvideo.uploadVideoSizeBytes"
              :title="formState[props.uploadType].uploadTitle"
              :percent="percent"
              :isAutoUpload="formState[props.uploadType].isAutoUpload"
              @uploadChangeFinished="uploadChangeFinished"
              v-if="props.uploadType == 'insertvideo'"
            ></videoUpload>
            <audioUpload
              :fileList="fileList_temp"
              :maxCount="1"
              :title="formState[props.uploadType].uploadTitle"
              :accept="fileLimit.music.uploadAudioSuffix"
              :isLimit="fileLimit.music.uploadAudioSizeBytes"
              :percent="percent"
              :isAutoUpload="formState[props.uploadType].isAutoUpload"
              @uploadChangeFinished="uploadChangeFinished"
              v-if="props.uploadType == 'music'"
            ></audioUpload>
            <!-- 附件上传 -->
            <fileUpload
              :fileList="fileList_temp"
              :maxCount="props.maxCount || 1000000000"
              :accept="fileLimit.attachment.uploadAttachmentSuffix || ''"
              :isLimit="fileLimit.attachment.uploadAttachmentSizeBytes"
              :isAutoUpload="formState[props.uploadType].isAutoUpload"
              :dislogVisible="dislogVisible"
              isInDialog="true"
              :isAttachment="true"
              @uploadChangeFinished="uploadChangeFinished"
              v-if="props.uploadType == 'attachment'"
            ></fileUpload>
            <uploadFile
              :fileList="fileList_temp"
              :maxCount="1"
              :accept="'doc'"
              :isLimit="fileLimit.img.uploadPicSize"
              :title="formState[props.uploadType].uploadTitle"
              :isAutoUpload="false"
              @uploadChangeFinished="uploadChangeFinished"
              v-if="props.uploadType == 'wordimage'"
              :percent="percent"
            >
            </uploadFile>

            <span class="tips" v-if="acceptType"
              >支持上传{{ acceptType }}格式</span
            >
            <span class="tips" v-if="limitSize"
              >(大小限制{{ limitSize }}KB)</span
            >
          </div>
        </div>
        <div class="flex" v-if="watermarkSet != 3">
          <span class="lables">是否添加水印:</span>
          <a-radio-group v-model:value="waterMark">
            <a-radio :value="1">是</a-radio>
            <a-radio :value="0">否</a-radio>
          </a-radio-group>
        </div>
        <div class="addSource">
          <div>
            <span class="lables">是否添加到资源库:</span>
            <a-radio-group v-model:value="statusSetting">
              <a-radio :value="1">是</a-radio>
              <a-radio :value="0">否</a-radio>
            </a-radio-group>
          </div>
          <div v-show="statusSetting == 1" class="sourceTree">
            <editSourceTree @selectKeys="selectKeys"></editSourceTree>
          </div>
        </div>
      </div>
      <div v-else>
        <resourceLibrary
          @emitSelectedKeys="emitSelectedKeys"
          :maxCount="
            props.uploadType == 'insertimage' ||
            props.uploadType == 'attachment'
              ? props.maxCount
              : 1
          "
          :accept="acceptType.split(',')"
          :limitSize="limitSize"
        >
        </resourceLibrary>
      </div>
    </template>
  </baseModal>
</template>
<script lang="ts" setup>
import { ref, watch, computed, nextTick, onMounted, reactive } from "vue";
import baseTabs from "@/components/tabs/baseTabs.vue";
import baseModal from "@/components/modal/baseModal.vue";
import uploadFile from "@/components/uploadDialog/uploadFile.vue";
import multiPictureUpload from "@/components/uploadDialog/multiPictureUpload.vue";
import videoUpload from "@/components/uploadDialog/videoUpload.vue";
import audioUpload from "@/components/uploadDialog/audioUpload.vue";
import fileUpload from "@/components/uploadDialog/fileUpload.vue";
import editSourceTree from "./sourceLibary/editSourceTree.vue";
import resourceLibrary from "@/components/uploadDialog/resourceLibrary.vue";
import { message } from "ant-design-vue";
import request from "@/api/index";
import { request as $axios } from "@/api/axios";
import { formItem } from "./uploadConfig/upload";
import { dataSourceType } from "../../type";
import { Console } from "console";
//props
const props = defineProps({
  formItem: {
    // 模型传过来的配置
    type: Object,
    default: {},
  },
  isVisible: {
    type: Boolean,
    default: false,
  },
  uploadType: {
    type: String,
    default: "",
  },
  description: {
    type: Boolean,
    default: false,
  },
  maxCount: {
    type: [Number],
    default: "",
  },
});
//emit
const emit = defineEmits([
  "uploadChangeFinished",
  "uploadFinished",
  "upload_remove_Finished",
  "handleCancle",
  "addDescription",
  "dislogVisible",
]);
//data
const modAlProps = reactive({
  width: "L",
  title:
    props.uploadType == "insertvideo"
      ? "上传视频"
      : props.uploadType == "music"
      ? "上传音频"
      : props.uploadType == "attachment"
      ? "上传文件"
      : "上传图片",
});
const videoUploadRef = ref<any>(null);
const formState = ref<dataSourceType>(formItem);
const optionsFile = ref<any[]>([]);
const statusSetting = ref<string | number>(0);
const waterMark = ref<string | number>(0);
const uploadType = ref(1);
const select_keys = ref<string>("");
const percent = ref<string | number>("0%");
const fileList_temp = ref<dataSourceType[]>([]);
const watermarkSet = ref<any>("");
// 模态框按钮
const buttons = ref<dataSourceType[]>([
  {
    text: "保存",
    "html-type": "submit",
    keepAlive: true,
    disabled: false,
  },
]);
const tabsList = [
  {
    tabName: "资源上传",
    key: 1,
  },
  {
    tabName: "资源库",
    key: 2,
  },
];
const fileLimit = ref<dataSourceType>({
  img: {},
  insertvideo: {},
  music: {},
  attachment: {},
});
let acceptType = ref("");
let limitSize = ref(0);
const dislogVisible = ref(props.isVisible);
// 资源库相关数据
const receiveSourceList = ref<dataSourceType[]>([]); // 资源库传来的选中数据
// watch
watch(
  () => props.isVisible,
  (newVal, oldVal) => {
    console.log(newVal, oldVal, "newVal, oldVal");
    dislogVisible.value = newVal;
    if (!newVal || newVal) {
      if (videoUploadRef.value?.fileName) {
        videoUploadRef.value.fileName = null;
        fileList_temp.value = [];
        percent.value = "0%";
      }
    }
  },
  { deep: true }
);
watch(
  () => props.uploadType,
  (newVal, oldVal) => {
    if (props.formItem) {
      formState.value[newVal] = Object.assign(
        {},
        formState.value[newVal],
        JSON.parse(JSON.stringify(props.formItem))
      );
    }
  },
  { deep: true, immediate: true }
);
watch(
  () => receiveSourceList.value,
  (newVal, oldVal) => {
    if (!newVal.length && buttons.value[0].text == "确定") {
      buttons.value[0].disabled = true;
    } else {
      buttons.value[0].disabled = false;
    }
  },
  { deep: true, immediate: true }
);
// computed

//methods
// 获取站点中文件相关配置
const getFilesSettings = async () => {
  let res = (await request.getFilesSettings()).fileUploadSetup || {};
  console.log([res.uploadAttachmentSuffix].join(","),'文件配置');
  
  let result = (await request.getFilesSettings()).waterMarkSetup || {};
  watermarkSet.value = result.watermarkSet;

  nextTick(() => {
    fileLimit.value.img = {
      uploadPicSuffix: res.uploadPicSuffix.join(","),
      uploadPicSize: res.uploadPicSizeBytes,
    };
    fileLimit.value.insertvideo = {
      uploadVideoSuffix: res.uploadVideoSuffix.join(","),
      uploadVideoSizeBytes: res.uploadVideoSizeBytes,
    };
    fileLimit.value.music = {
      uploadAudioSuffix: res.uploadAudioSuffix.join(","),
      uploadAudioSizeBytes: res.uploadAudioSizeBytes,
    };
    fileLimit.value.attachment = {
      uploadAttachmentSuffix:
        res.uploadAttachmentSuffixType == 1
          ? ""
          : [res.uploadAttachmentSuffix].join(","),
      uploadAttachmentSizeBytes: res.uploadAttachmentSizeBytes,
    };
    if (
      props.uploadType == "simpleupload" ||
      props.uploadType == "insertimage"
    ) {
      acceptType.value = fileLimit.value.img.uploadPicSuffix;
      limitSize.value = fileLimit.value.img.uploadPicSizeBytes / 1024;
    } else if (props.uploadType == "insertvideo") {
      acceptType.value = fileLimit.value.insertvideo.uploadVideoSuffix;
      limitSize.value = fileLimit.value.insertvideo.uploadVideoSizeBytes / 1024;
    } else if (props.uploadType == "music") {
      acceptType.value = fileLimit.value.music.uploadAudioSuffix;
      limitSize.value = fileLimit.value.music.uploadAudioSizeBytes / 1024;
    } else if (props.uploadType == "attachment") {
      acceptType.value = fileLimit.value.attachment.uploadAttachmentSuffix;
      limitSize.value =
        fileLimit.value.attachment.uploadAttachmentSizeBytes / 1024;
    }
  });
};
//改变头部tab切换
const changeTopTabs = (activeKey: number) => {
  uploadType.value = activeKey;
  if (activeKey == 1) {
    buttons.value[0].text = "保存";
    buttons.value[0].disabled = false;
  } else {
    if (!receiveSourceList.value.length) {
      buttons.value[0].disabled = true;
    } else {
      buttons.value[0].disabled = false;
    }
    buttons.value[0].text = "确定";
  }
};
const handleCancle = () => {
  emit("handleCancle");
};
const uploadChangeFinished = (val: any) => {
  optionsFile.value = [];
  nextTick(() => {
    if (Array.isArray(val)) {
      optionsFile.value = val;
    } else {
      optionsFile.value = [val];
    }
  });
};
const handleOk = () => {
  if (uploadType.value == 1) {
    if (optionsFile.value.length == 0) {
      message.warning("请选择文件！");
    }
    let fileList = optionsFile.value.length;
    optionsFile.value.forEach((item: any) => {
      buttons.value[0].disabled = true;
      // console.log(item,'item婆婆婆婆');
      item.options.file.status = "success";
      const param = new FormData(); // 创建form对象
      if(item.isAnnex) {
        param.append("isAnnex", item.isAnnex);
      }
      param.append("files", item.options.file, item.options.file.name); // 通过append向form对象添加数据
      param.append("watermark", waterMark.value ? "true" : "false");
      param.append("resourceVisible", statusSetting.value ? "true" : "false");
      if (statusSetting.value) {
        param.append("groupId", select_keys.value || "0");
      }
      let headers: Record<string, any> = {
        "Content-Type":
          "multipart/form-data; boundary=----WebKitFormBoundary1kBB8pgsKICPa9RM",
        noWatermark: 1,
      };
      $axios
        .post("/server-admin/res/upload", param, {
          headers: headers,
          onUploadProgress: ({ total, loaded }) => {
            if (total) {
              percent.value =
                Math.round((loaded / total) * 100) < 100
                  ? Math.round((loaded / total) * 100).toFixed(1)
                  : (100 - Math.random() * 10).toFixed(1);
                  console.log(percent.value, "percent.value");
              if (item.options.onProgress) {
                //留足大图片渲染时间
                item.options.onProgress(
                  { percent: Math.round((loaded / total) * 100).toFixed(2) },
                  item
                );
              }
            }
          },
        })
        .then(async (res: any) => {
          if (res.data.code == "00000 00000") {
            fileList--;
            await emit(
              "uploadFinished",
              getHtml(
                res.data.data[0].url,
                res.data.data[0].oriFileName || res.data.data[0].filename
              ),
              res.data.data,
              item.description
            );
            if (fileList == 0) {
              emit("dislogVisible", false);
              buttons.value[0].disabled = false;
              setTimeout(() => {
                fileList_temp.value = [];
                optionsFile.value = [];
                dislogVisible.value = false;
              }, 40);
            }

            message.success(res.data.message);
          } else {
            message.error(res.data.message);
            setTimeout(() => {
                fileList_temp.value = [];
                optionsFile.value = [];
                buttons.value[0].disabled = false;
              }, 40);
          }
        })
        .catch((err) => {});
    });
  } else {
    receiveSourceList.value.forEach((item: dataSourceType) => {
      let obj = {
        url: item.resourceUrl,
        filename: item.resourceAlias,
        id: item.id,
        oriFileName: item.oriFileName,
      };
      emit(
        "uploadFinished",
        getHtml(obj.url, obj.oriFileName || obj.filename),
        [obj],
        ""
      );
    });
  }
};
const getHtml = (url: any, name: any) => {
  console.log(url, name, "url, name");
  let html = "";
  switch (props.uploadType) {
    case "insertvideo":
      if (url.substr(-4) === ".flv") {
        html = `<p style="height:15px"></p><p><embed src='${url}' style='max-width:100%'/></p>`;
      } else {
        html = `<p style="height:15px"></p><p><video controls src='${url}' controlslist='nodownload' style='max-width:100%'>no video</video></p>`;
      }
      break;
    case "music":
      html = `<p style="height:15px"></p><p><audio class="voice" controls src='${url}'>no audio</audio></p>`;
      break;
    case "attachment":
      html = `<a href='${url}' download='${url}'>${name}</a>`;
      break;
    default:
      html = `<p style="text-align: center"><img src='${url}' style='max-width:100%'/></p>`;
  }
  return html;
};
const addDescription = (index: any, val: {}) => {
  emit("addDescription", index, val);
};
const emitSelectedKeys = (val: any) => {
  // 资源库或者共享资源传来的选中的数据
  receiveSourceList.value = JSON.parse(JSON.stringify(val));
};
const selectKeys = (val: any) => {
  // 资源分组传来的选中的数据
  select_keys.value = val;
};
const checkWater = () => {
  // $axios.fetchSiteManageGetSiteDetail_extendInfo()
};
//onMounted
onMounted(() => {
  getFilesSettings();
});
</script>
<style lang="scss" scoped>
.flex {
  margin-top: 24px;
  display: flex;
  align-items: baseline;
}

.flex-colunm {
  flex-direction: column;
}

.ant-tabs {
  // margin-bottom: 24px;
}

.lables {
  margin-right: 12px;
  width: 115px;
  height: 22px;
  font-size: 14px;
  font-family: PingFang SC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
  line-height: 22px;
  text-align: right;
}

.tips {
  margin-top: 8px;
  height: 20px;
  font-size: 12px;
  font-family: PingFang SC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.45);
  line-height: 20px;
  display: inline-block;
}

.addSource {
  margin-top: 24px;
}

.sourceTree {
  margin-top: 24px;
  width: 480px;
  height: 304px;
  background: #ffffff;
  border-radius: 2px 2px 2px 2px;
  opacity: 1;
  border: 1px solid rgba(0, 0, 0, 0.15);
  overflow: auto;
  padding: 16px;
  box-sizing: border-box;
  margin-left: 120px;
}
</style>
<style lang="scss">
.uploadDialong {
  .ant-input-textarea-show-count::after {
    position: absolute;
    right: 12px;
    bottom: 6px;
    line-height: 1;
  }
}
</style>
